﻿using CoreDomain.BusinessCore;
using DomainService.IService;
using DomainService.IService.Sys;
using Infrastructure;
using Infrastructure.IRepository.Sys;
using Infrastructure.Repository.Sys;
using Model;
using Model.BusinessModel.InPut;
using Model.BusinessModel.OutPut;
using Model.BusinessModel.OutPut.sys;
using Model.DomainModel.Sys;
using System.Reflection.PortableExecutable;
using Utility;
using Utility.Enum;

namespace DomainService.Service.Sys
{
    /// <summary>
    /// 系统服务接口实现
    /// </summary>
    public class SysSystemService : ISysSystemService
    {
        #region 构造实例化

        /// <summary>
        /// 系统底层仓储
        /// </summary>
        private readonly ISysSystemRepository _sysSystemRepository;

        /// <summary>
        /// 基础服务
        /// </summary>
        private readonly IBaseService _baseService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sysSystemRepository"></param>
        public SysSystemService(ISysSystemRepository sysSystemRepository, IBaseService baseService)
        {
            _sysSystemRepository = sysSystemRepository;
            _baseService = baseService;
        }

        #endregion

        #region 业务逻辑

        /// <summary>
        ///  获取项目系统数据
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        public List<SysSystemOutPut> GetSystemList(string? corporationKey)
        {
            var result = _baseService.GetAuthWhere(RuleTypeEnum.DataRowRule, "ss");
            string? authWhere = string.Empty;
            if (result.success) { authWhere = result.data[0]; }
            else
                ExceptionHelper.ThrowBusinessException(result.msg);
            var corporationSystemList = _sysSystemRepository.GetSystemList(corporationKey, authWhere);
            return corporationSystemList;
        }

        /// <summary>
        /// 获取当前登录人员所在公司的所有系统
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns>返回所有系统</returns>
        public ReceiveStatus<SelectOutPut> GetSystemByCorporationKey(string corporationKey)
        {
            ReceiveStatus<SelectOutPut> receiveStatus = new();
            //if (string.IsNullOrWhiteSpace(corporationKey))
            //    return ExceptionHelper<SelectOutPut>.CustomExceptionData("公司key为空,请先登录");
            List<SelectOutPut> selectOutPuts = [];
            var list = _sysSystemRepository.GetAll(BaseSqlRepository.sysSystem_selectAllSql).Where(f => f.CorporationKey == corporationKey);
            foreach (var item in list)
            {
                SelectOutPut selectOutPut = new()
                {
                    value = item.SystemKey ?? string.Empty,
                    label = item.SystemName ?? string.Empty,
                    disabled = item.IsOpen == true ? false : true,
                };
                selectOutPuts.Add(selectOutPut);
            }
            receiveStatus.data = selectOutPuts;
            return receiveStatus;
        }

        /// <summary>
        /// 新增系统
        /// </summary>
        /// <param name="sysSystem">系统数据</param>
        public ReceiveStatus Insert(SysSystem sysSystem)
        {
            ReceiveStatus receiveStatus = new();
            sysSystem.SystemKey = Guid.NewGuid().ToString();
            var result = Validate(sysSystem);
            if (!result.success)
                return result;
            _sysSystemRepository.Insert(sysSystem, BaseSqlRepository.sysSystem_insertSql);
            return receiveStatus;
        }

        /// <summary>
        /// 修改系统
        /// </summary>
        /// <param name="sysSystem">系统数据</param>
        public ReceiveStatus Update(SysSystem sysSystem)
        {
            ReceiveStatus receiveStatus = new();
            var model = _sysSystemRepository.GetByKey(sysSystem.SystemKey.ToString(), BaseSqlRepository.sysSystem_selectByKeySql);
            if (model == null)
                return ExceptionHelper.CustomException(string.Format("系统名称【{0}】不存存在或已删除!", sysSystem.SystemName));
            var result = Validate(sysSystem);
            if (!result.success)
                return result;

            if (sysSystem.SystemKey == Const.OverallAuth_SystemKey)
            {
                return ExceptionHelper.CustomException(string.Format("系统【{0}】为演示系统，禁止操作。", model.SystemName));
            }
            _sysSystemRepository.Update(sysSystem, BaseSqlRepository.sysSystem_updateSql);
            return receiveStatus;
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="sysSystem">系统数据</param>
        /// <returns></returns>
        public ReceiveStatus Validate(SysSystem sysSystem)
        {
            ReceiveStatus receiveStatus = new ReceiveStatus();
            /*
            新增/修改前验证
            1、系统名称和编码不能出现重复
            2、公司不能为空
            */

            if (string.IsNullOrWhiteSpace(sysSystem.SystemName))
                return ExceptionHelper.CustomException("系统名称不能为空!");
            if (string.IsNullOrWhiteSpace(sysSystem.SystemCode))
                return ExceptionHelper.CustomException("系统编码不能为空!");
            if (string.IsNullOrWhiteSpace(sysSystem.CorporationKey.ToString()))
                return ExceptionHelper.CustomException("所属公司不能为空!");

            var sysSystemList = _sysSystemRepository.GetSystemMsg(sysSystem.SystemName, sysSystem.SystemCode);

            foreach (var item in sysSystemList)
            {
                if (sysSystem.SystemName.ToLower() == item.SystemName.ToLower() && sysSystem.SystemKey != item.SystemKey)
                    return ExceptionHelper.CustomException(string.Format("系统名称【{0}】已存在,请重新输入", sysSystem.SystemName));
                if (sysSystem.SystemCode.ToLower() == item.SystemCode.ToLower() && sysSystem.SystemKey != item.SystemKey)
                    return ExceptionHelper.CustomException(string.Format("系统编码【{0}】已存在,请重新输入", sysSystem.SystemCode));
            }

            return receiveStatus;
        }

        /// <summary>
        /// 设置系统是否启用
        /// </summary>
        /// <param name="updateIsOpenInPut">修改模型</param>
        /// <returns></returns>
        public ReceiveStatus SetSystemIsOpen(UpdateIsOpenInPut updateIsOpenInPut)
        {
            ReceiveStatus receiveStatus = new();
            if (updateIsOpenInPut == null)
                return ExceptionHelper.CustomException("请选择系统");
            if (updateIsOpenInPut.Keys.Count == 0)
                return ExceptionHelper.CustomException("请选择系统");

            var systemKey = updateIsOpenInPut.Keys.FirstOrDefault(f => f == Const.OverallAuth_SystemKey);
            if (!string.IsNullOrWhiteSpace(systemKey))
            {
                var model = _sysSystemRepository.GetByKey(systemKey, BaseSqlRepository.sysSystem_selectByKeySql);
                return ExceptionHelper.CustomException(string.Format("系统【{0}】为演示系统，禁止操作。", model.SystemName));
            }

            //写入数据库，加入事务
            TransactionHelper.ExecuteTransaction(() =>
            {
                _sysSystemRepository.SetSystemIsOpen(updateIsOpenInPut.Keys, updateIsOpenInPut.IsOpen);
            });

            return receiveStatus;
        }
        #endregion
    }
}
